#include <iostream>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <thread>
#include <random>
using namespace std;

mutex mtx;
condition_variable cv;
queue<int> test;
constexpr int MAX_SIZE = 100;

void producer()
{
    std::random_device rd;  // 将用于为随机数引擎获得种子
  std::mt19937 gen(rd()); // 以播种标准 mersenne_twister_engine
  std::uniform_int_distribution<> dis(1, 10000);
//   std::uniform_int_distribution<> utime(1, 3);
    while(true)
    {
        // 如果不用信号量的话，那么还是每次只有一个线程能进来这边进行生产
        // 生产生产的快
        this_thread::sleep_for(chrono::milliseconds(50));
        // lock_guard<mutex> lk(mtx);
        unique_lock<mutex> lck(mtx);
        cv.wait(lck, [](){return test.empty() && test.size() <= MAX_SIZE;});
        
        test.push(dis(gen));
        cout << "thread_id " << this_thread::get_id() << " produce " << test.front() << endl;
		lck.unlock();
        cv.notify_one();
        // sleep(2);
    }
}

void consumer()
{
    while(true)
    {
        this_thread::sleep_for(chrono::milliseconds(50));
        unique_lock<mutex> lck(mtx);
        cv.wait(lck, [](){return !test.empty();});  // 阻塞 直到队列不是空的
        cout << "thread_id " << this_thread::get_id() << " comsumer" << test.front() << endl;
        test.pop();
        lck.unlock();
        cv.notify_one();
        // sleep(2);
    }
}

int main()
{
    thread th1(producer);
    thread th3(producer);
    thread th4(producer);
    thread th5(producer);
    thread th2(consumer);
    // thread th3(consumer);
    th1.join();
    th2.join();
    th3.join();
    th4.join();
    th5.join();
    // th3.join();
    return 0;
}
